﻿#region Using References

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

#endregion

namespace Beaker.OpenCube.Converters
{
	class BooleanConverter
		: DependencyObject, IValueConverter
	{
		public static readonly DependencyProperty TrueValueProperty =
			DependencyProperty.Register(
				"TrueValue",
				typeof( object ),
				typeof( BooleanConverter ),
				new PropertyMetadata( null )
			);

		public object FalseValue
		{
			get { return GetValue( FalseValueProperty ); }
			set { SetValue( FalseValueProperty, value ); }
		}

		public static readonly DependencyProperty FalseValueProperty =
			DependencyProperty.Register(
				"FalseValue",
				typeof( object ),
				typeof( BooleanConverter ),
				new PropertyMetadata( null )
			);

		public object TrueValue
		{
			get { return GetValue( TrueValueProperty ); }
			set { SetValue( TrueValueProperty, value ); }
		}

		public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
		{
			// default to false
			bool booleanValue = false;

			if( value is Boolean )
			{
				booleanValue = (bool)value;
			}
			else if( value is int || value is short || value is byte || value is sbyte || value is ushort || value is uint || value is long || value is ulong )
			{
				// convert to biggest number any number should be able to convert to, without overflow problems
				long tempValue = System.Convert.ToInt64( value );
				// if value is non-null, it's assumed to be true
				booleanValue = tempValue != 0;
			}
			else
			{
				// for any non boolean it's true when object has a value
				booleanValue = value != null;
			}

			return booleanValue 
				? TrueValue
				: FalseValue;
		}

		public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
		{
			throw new NotImplementedException();
		}
	}
}
